from .models import Project, Channel
from utils.serializers import CustomModelSerializer
from rest_framework import serializers


class ProjectSerializer(CustomModelSerializer):
    """
    项目管理-序列化器
    """

    class Meta:
        model = Project
        fields = '__all__'
        read_only_fields = ['id']


class ChannelSerializer(CustomModelSerializer):
    """
    渠道管理-序列化器
    """

    project_name = serializers.CharField(source='project.name')

    class Meta:
        model = Channel
        fields = '__all__'
        read_only_fields = ['id']


class ChannelCreateUpdateSerializer(CustomModelSerializer):
    """
    渠道管理-序列化器
    """

    def create(self, validated_data):
        validated_data['db_password'] = Channel.make_password(validated_data['db_password'])
        return super().create(validated_data)

    class Meta:
        model = Channel
        fields = '__all__'
        read_only_fields = ['id']


class ChannelSimpleSerializer(CustomModelSerializer):
    """
    渠道管理-序列化器
    """
    title = serializers.CharField(source='channel_name')
    value = serializers.CharField(source='id')

    class Meta:
        model = Channel
        fields = ('id', 'title', 'value')
        read_only_fields = ['id']


class ProjectChannelSerializer(CustomModelSerializer):
    """
    项目渠道树-序列化器
    """
    title = serializers.CharField(source='name')
    value = serializers.CharField(source='id')
    children = serializers.SerializerMethodField()

    def get_children(self, obj):
        return ChannelSimpleSerializer(obj.channel_set.all(), many=True).data

    class Meta:
        model = Project
        fields = ('id', 'title', 'value', 'children')
        read_only_fields = ['id']
